package com.wuzhiming.istudy.controller;

import com.alibaba.fastjson.JSONObject;
import com.wuzhiming.istudy.pojo.Collection;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

/**
 * @ClassName: CollectionController
 * @Description: 收藏课程控制器
 * @Author:zhimingw
 * @Version 1.0
 * @since 2022/3/16 20:01
 */
@RestController
public class CollectionController extends BaseController{

    /**
    * @Description: 添加收藏
    * @Param: [collection]
    * @return: java.lang.String
    * @Author: zhimingw
    * @Date: 2022/3/24
    */
    @PostMapping("/addCollection")
    public String addCollection(Collection collection){
        List<Collection> oldcollection = collectionService.getCollection(collection);
        collection.setTime(new Date());
        if(oldcollection.size()>0){{
            //如果已经存在该数据,更新
            collection.setStatus(1);
            if(collectionService.cancleCollection(collection)){
                result.setCode(200);
            }else{
                result.setCode(500);
            }
        }}else{
            if(collectionService.addCollection(collection)){
                result.setCode(200);
            }else{
                result.setCode(500);
            }
        }
        return JSONObject.toJSONString(result);
    }

    /**
    * @Description: 取消收藏
    * @Param: [collection]
    * @return: java.lang.String
    * @Author: zhimingw
    * @Date: 2022/3/24
    */
    @PostMapping("/cancleCollection")
    public String cancleCollection(Collection collection){
        System.out.println("进入cancle");
        collection.setStatus(0);
        if(collectionService.cancleCollection(collection)){
            result.setCode(200);
        }else{
            result.setCode(500);
        }
        return JSONObject.toJSONString(result);
    }

    /**
    * @Description: 根据条件获取用户收藏
    * @Param: [id]
    * @return: java.lang.String
    * @Author: zhimingw
    * @Date: 2022/3/24
    */
    @GetMapping("/getCollections")
    public String getCollections(Collection collection){
        collection.setStatus(1);
        List<Collection> collections = collectionService.getCollection(collection);
        if(collections.size()>0){
            result.setCode(200);
        }else{
            result.setCode(500);
        }
        result.setData(collections);
        return JSONObject.toJSONString(result);
    }
}
